
import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return x*x-1

'''
# 画图观察 f(x) 曲线
x = np.arange(0,np.pi/2,0.1)
y = f(x)
plt.plot(x,y,label="$y=cos(x) -x$")
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_position(('data',0))
plt.xlabel("x",fontsize=15)
plt.ylabel("y",fontsize=15)
plt.legend()
#plt.show()
'''

# 二分法方程求根
def bisection(a,b,f,precision):
    if f(a) * f(b) > 0 :
        print("bisection: invalid a, b"); exit(1)
    while( abs(b-a) > precision ):
        c = (a+b)/2
        print("a=",a,", b=",b,", c=",c)
        if f(a) * f(c) <= 0:
            b = c
        else:
            a = c
    return (a+b)/2, (b-a)/2

z = bisection(0,3,f,1e-5)
print( "root of f(x)=0 is ", z[0], "error =",z[1] )